package me.ezjs.framework.core.dao.hibernate;

import java.util.ArrayList;
import java.util.List;

/**
 * 表与表之间的关联关系.属于多叉树.
 * <p/>
 * Created by zero-mac on 16/3/11.
 */
public class TableNode {
    public static final String ALIAS_PRE = "obj";//默认的别名前缀

    private List<TableNode> children; // 子节点

    private TableNode father;//父节点

    private String tableName;//表名
    private JoinType joinType;//连接类型
    private String aliasName;//别名

    /**
     * 创建根节点
     *
     * @param tableName
     */
    public TableNode(String tableName) {
        this.tableName = tableName;
        this.aliasName = ALIAS_PRE + "0";
    }

    public TableNode(String tableName, JoinType type) {
        this.tableName = tableName;
        this.joinType = type;
    }

    /**
     * 添加子节点,返回新创建的节点
     *
     * @param tableName
     * @param type
     * @return
     */
    public TableNode addChild(String tableName, JoinType type) {
        TableNode child = new TableNode(tableName, type);
        child.add2Father(this);
        return child;
    }

    private void add2Father(TableNode father) {
        this.setFather(father);
        List<TableNode> children = father.getChildren();
        children.add(this);

        this.aliasName = father.getAliasName() + father.getChildrenNum();
    }

    public List<TableNode> getChildren() {
        if (children == null) {
            children = new ArrayList<>();
        }
        return children;
    }

    public static void generateJoinHqlOfFromClause(TableNode root, StringBuilder sb) {
        for (TableNode child :
                root.getChildren()) {
            JoinType joinType = child.getJoinType();
            String joinClause = joinType.getSql() + root.getAliasName() + "." +
                    child.getTableName() + " " + child.getAliasName();
            sb.append(joinClause);

            if (child.getChildrenNum() > 0) {
                generateJoinHqlOfFromClause(child, sb);
            }
        }
    }

    public int getChildrenNum() {
        if (children == null) {
            return 0;
        }
        return children.size();
    }

    public TableNode getFather() {
        return father;
    }

    public void setFather(TableNode father) {
        this.father = father;
    }

    public String getTableName() {
        return tableName;
    }

    public void setTableName(String tableName) {
        this.tableName = tableName;
    }

    public JoinType getJoinType() {
        return joinType;
    }

    public void setJoinType(JoinType joinType) {
        this.joinType = joinType;
    }

    public String getAliasName() {
        return aliasName;
    }

    public void setAliasName(String aliasName) {
        this.aliasName = aliasName;
    }
}
